<?php

namespace Base;

use W3\Widget;
use W3\Router;
use W3\Config;
use W3\Db\Query;
use function do_action;

/**
 * 用户基类
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Users extends Widget
{
    /**
     * 获取查询对象
     *
     * @return Query
     * @throws Exception
     */
    public function select(...$args): Query
    {
		return do_action( 
		    $this->parameter->main . '.select',
			$this,
			false,
			$this->db->select(...$args)->from('table.users')
		);
    }
	
    /**
     * 将每行的值压入堆栈
     *
     * @access public
     * @param array $value 每行的值
     * @return array
     */
    public function push(array $value)
    {
        $value = $this->filter($value);
        return parent::push($value);
    }

    /**
     * 通用过滤器
     *
     * @access public
     * @param array $value 需要过滤的行数据
     * @return array
     */
    public function filter(array $value)
    {
		if (isset($value['uid'], $value['name'])) {	

            $value['permalink'] = Router::buildUrl('author', $value);
		}

		/** 插件接口 */
		$value = do_action('users_filter', $this, false, $value);
		
        return $value;
    }

    /**
     * 输出用户头像
     *
     * @access public
     * @return void
     */
    public function ___avatar()
    {
        return $this->assetUrl('images/avatar-default.png', false);
    }

    /**
     * 个人选项
     *
     * @return Config
     * @throws Exception
     */
    protected function ___options(): Config
    {
        $rows = $this->db->select()
            ->from('table.options')
			->where('uid = ?', $this->uid)
			->get();
			
        $options = [];
        foreach ($rows as $row) 
		{
            $options[$row['name']] = $row['value'];
        }

        return Config::make($options);
    }

    /**
     * 输出作者相关
     *
     * @param boolean|null $autoLink 是否自动加上链接
     * @param boolean|null $noFollow 是否加上nofollow标签
     */
    public function autoLink(?bool $autoLink = null, ?bool $noFollow = null)
    {
        $autoLink = (null === $autoLink) ? $this->options->commentsShowUrl : $autoLink;
        $noFollow = (null === $noFollow) ? $this->options->commentsUrlNofollow : $noFollow;

        if ($this->url && $autoLink) {
            echo '<a href="' . $this->url . '"'
                . ($noFollow ? ' rel="external nofollow"' : null) . '>' . $this->name . '</a>';
        } else {
            echo $this->name;
        }
    }

}
